package com.wolfking.web.ssoauth.controller;

import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import com.google.common.collect.Maps;
import com.wolfking.back.core.annotation.ssoauth.Sign;
import com.wolfking.back.core.bean.Dict;
import com.wolfking.back.core.bean.Office;
import com.wolfking.back.core.bean.PageInfo;
import com.wolfking.back.core.bean.User;
import com.wolfking.back.core.config.SsoConfig;
import com.wolfking.back.core.exception.ExceptionMessage;
import com.wolfking.back.core.feignclient.DictFeignClient;
import com.wolfking.back.core.feignclient.OfficeFeignClient;
import com.wolfking.back.core.feignclient.UserFeignClient;
import com.wolfking.back.core.util.DataEntityUtil;
import com.wolfking.back.core.util.PasswordUtil;

/**
 * 用户的controller
 * 
 * @author wolfking@赵伟伟
 * @mail zww199009@163.com
 * @创作日期 2017年5月6日 下午9:01:37
 * @copyright wolfking
 */
@Controller
@RequestMapping("/user")
public class UserController {

	private Logger logger = LoggerFactory.getLogger(getClass());

	@Autowired
	private UserFeignClient userFeignClient;

	@Autowired
	private DictFeignClient dictFeignClient;

	@Autowired
	private SsoConfig ssoConfig;

	@Autowired
	private OfficeFeignClient officeFeignClient;

	/**
	 * 用户修改密码页面的GET
	 * 
	 * @param model
	 * @param user
	 * @return
	 */
	@Sign
	@RequestMapping(value = "/modifyPwd", method = RequestMethod.GET)
	public String modifyPwdGet() {
		return "user/modifyPwd";
	}

	/**
	 * 用户修改密码的操作
	 * 
	 * @param model
	 * @param user
	 * @return
	 */
	@Sign
	@RequestMapping(value = "/modifyPwd", method = RequestMethod.POST)
	public String modifyPwdPost(Model model, User user, @RequestParam String oldPassword,
			@RequestParam String newPassword, RedirectAttributes redirectAttributes) {
		try {
			userFeignClient.modifyPwd(user.getId(), oldPassword, newPassword);
			redirectAttributes.addFlashAttribute("message", "用户修改密码成功");
			return "redirect:" + ssoConfig.getSelfRootUrl() + "/user/userInfo";
		} catch (Exception e) {
			try {
				logger.error("", e);
				ExceptionMessage ex = ExceptionMessage.parse(e);
				model.addAttribute("message", ex.getMessage());
			} catch (Exception ee) {
				logger.error("", e);
				model.addAttribute("message", "用户修改密码异常");
			}
			redirectAttributes.addFlashAttribute("message", "修改密码成功");
			return "user/modifyPwd";
		}
	}

	/**
	 * 用户个人信息页面
	 * 
	 * @param model
	 * @param user
	 * @return
	 */
	@Sign
	@RequestMapping(value = "/userInfo", method = { RequestMethod.GET, RequestMethod.POST })
	public String infoPost(Model model, User user, User current, HttpServletRequest request) {
		if ("POST".equals(request.getMethod().toUpperCase())) {
			DataEntityUtil.assemblyDataEntity(user, current);
			userFeignClient.updateUser(user);
			model.addAttribute("message", "修改用户信息成功");
		}
		user = userFeignClient.getUser(current.getId()).getBody();
		List<Dict> dicts = dictFeignClient.getByType("sys_user_type").getBody();
		Office office = officeFeignClient.getOffice(user.getOfficeId()).getBody();
		Office company = officeFeignClient.getOffice(user.getCompanyId()).getBody();
		model.addAttribute("dicts", dicts);
		model.addAttribute("user", user);
		model.addAttribute("office", office);
		model.addAttribute("company", company);
		return "user/userInfo";
	}

	/**
	 * 用户的编辑页面
	 * 
	 * @param model
	 * @param id
	 * @return
	 */
	@Sign
	@RequestMapping(value = "/edit", method = RequestMethod.GET)
	public String editGet(Model model, @RequestParam(required = false) String id) {
		User user = new User();
		Office office = new Office();
		Office company = new Office();
		if (StringUtils.isNotBlank(id))
			user = userFeignClient.getUser(id).getBody();
		model.addAttribute("user", user);
		List<Dict> typeDicts = dictFeignClient.getByType("sys_user_type").getBody();
		model.addAttribute("typeDicts", typeDicts);
		List<Dict> loginDicts = dictFeignClient.getByType("yes_no").getBody();
		model.addAttribute("loginDicts", loginDicts);
		if (StringUtils.isNotEmpty(id)) {
			office = officeFeignClient.getOffice(user.getOfficeId()).getBody();
			company = officeFeignClient.getOffice(user.getCompanyId()).getBody();
		}
		model.addAttribute("office", office);
		model.addAttribute("company", company);
		return "user/edit";
	}

	/**
	 * 用户修改
	 * 
	 * @param model
	 * @param user
	 * @param redirectAttributes
	 * @param current
	 * @return
	 */
	@Sign
	@RequestMapping(value = "/edit", method = RequestMethod.POST)
	public String editPost(Model model, User user, RedirectAttributes redirectAttributes, User current,
			@RequestParam(required = false) String newPassword) {
		if (StringUtils.isNoneEmpty(newPassword))
			user.setPassword(PasswordUtil.entryptPassword(newPassword));
		DataEntityUtil.assemblyDataEntity(user, current);
		if (StringUtils.isNotBlank(user.getId())) {
			userFeignClient.updateUser(user);
			redirectAttributes.addFlashAttribute("message", "修改用户成功");
		} else {
			userFeignClient.addUser(user);
			redirectAttributes.addFlashAttribute("message", "添加用户成功");
		}
		return "redirect:" + ssoConfig.getSelfRootUrl() + "/user/list";
	}

	/**
	 * 用户列表页
	 * 
	 * @param model
	 * @param user
	 * @param current
	 * @return
	 */
	@Sign
	@RequestMapping(value = "/list", method = { RequestMethod.GET, RequestMethod.POST })
	public String list(Model model, User user, @RequestParam(defaultValue = "1") int pageNum,
			@RequestParam(defaultValue = "10") int pageSize, User current) {
		Office office = new Office();
		Office company = new Office();
		if (StringUtils.isNotEmpty(user.getOfficeId()))
			office = officeFeignClient.getOffice(user.getOfficeId()).getBody();
		if (StringUtils.isNotEmpty(user.getCompanyId()))
			company = officeFeignClient.getOffice(user.getCompanyId()).getBody();
		model.addAttribute("office", office);
		model.addAttribute("company", company);
		Map<String, String> officeMap = Maps.newHashMap();
		List<Office> offices = officeFeignClient.getAllOffice().getBody();
		for (Office o : offices)
			officeMap.put(o.getId(), o.getName());
		model.addAttribute("officeMap", officeMap);
		PageInfo<User> page = userFeignClient.pageUser(user, pageNum, pageSize).getBody();
		model.addAttribute("page", page);
		return "user/list";
	}

	/**
	 * 用户的index主页
	 * 
	 * @return
	 */
	@Sign
	@RequestMapping(value = "/index", method = RequestMethod.GET)
	public String userIndex() {
		return "user/index";
	}

	@Sign
	@ResponseBody
	@RequestMapping("/checkLoginName")
	public boolean checkLoginName(@RequestParam String loginName, @RequestParam String oldLoginName) {
		if (loginName != null && loginName.equals(oldLoginName)) {
			return true;
		} else if (loginName != null) {
			User user = new User();
			user.setLoginName(loginName);
			List<User> list = userFeignClient.seleteAccuracy(user).getBody();
			return list.size() == 0;
		}
		return false;
	}
}
